package application2.servlet;

import application2.contorller.InputController;
import application2.contorller.SaveProductController;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 专门用来进行处理请求转发的
 */
@WebServlet(name = "DispatcherServlet", urlPatterns = {"/product_input2.action", "/product_save2.action"})
public class DispatcherServlet extends HttpServlet {

    private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1、接收并处理路径
        String uri = request.getRequestURI();
        int lastIndex = uri.indexOf("/");
        String action = uri.substring(lastIndex+1);

        request.setCharacterEncoding("UTF-8");

        // 2、进行视图转发
        String dispatcherUri = null;
        if (action.equals("product_input2.action")){
            InputController inputController = new InputController();
            dispatcherUri = inputController.handleRequest(request,response);
        } else if (action.equals("product_save2.action")){
            SaveProductController saveProductController = new SaveProductController();
            dispatcherUri = saveProductController.handleRequest(request,response);
        }

        if (dispatcherUri !=null){
            RequestDispatcher dispatcher = request.getRequestDispatcher(dispatcherUri);
            dispatcher.forward(request,response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        process(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        process(req, resp);
    }
}
